<?php
/* ******************************
 *	Product Price List aJax actions
 * ******************************
 */
 
include('../../includes/classes/core.php');
$action 	= $_REQUEST['act'];
$user_id	= $_SESSION['USERID'];
$error 		= '';
$data 		= '';
	
switch ($action) {
    case 'get_add_page':
    	$page		= GetPage();
		$data		= array('page'	=> $page);
		
        break;
    case 'get_edit_page':
	    $prod_id	= $_REQUEST['id'];
		$page		= GetPage(GetProduct($prod_id));
        
        $data 		= array('page'	=> $page);
        
        break;
    case 'get_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];
	    
        $rResult = mysql_query("	SELECT		`pricelist`.`id` AS `id`, 
												`production`.`name`, 
												ROUND(`reserve`.`price` , 2) AS `price`,
												`pricelist`.`price` AS `pPrice`, 
												`pricelist`.`price_wholesale` AS `pwPrice`
									FROM  		`pricelist`
									LEFT JOIN   `production`
										ON		`pricelist`.`production_id` = `production`.`id`
									LEFT JOIN	`reserve`
										ON		`pricelist`.`production_id` = `reserve`.`production_id`
        							WHERE		`pricelist`.`actived` = 1
									GROUP BY	`reserve`.`production_id`");
		
		$data = array(
			"aaData"	=> array()
		);
		
		while ( $aRow = mysql_fetch_array( $rResult ) )
		{
			$row = array();
			for ( $i = 0 ; $i < $count ; $i++ )
			{
				/* General output */
				$row[] = $aRow[$i];
				if($i == ($count - 1)){
					$row[] = '<input type="checkbox" name="check_' . $aRow[$hidden] . '" class="check" value="' . $aRow[$hidden] . '" />';
				}
			}
			$data['aaData'][] = $row;
		}
		
        break;
    case 'get_price':
		$prod_name	= $_REQUEST['p_name'];
		$prod_id 	= GetProductID($prod_name);
		
       	$self_price = number_format(GetSelfPrice($prod_id), 2, '.', '');
       	$last_price = number_format(GetLastPrice($prod_id), 2, '.', '');
       	
       	$data = array('self_price' => $self_price,
       				  'last_price' => $last_price
       	);

        break;
    case 'save_prod':
		$price_id 		= $_REQUEST['id'];
		
    	$prod_name 		= $_REQUEST['n'];
		$sp_price	 	= $_REQUEST['sp'];
		$sb_price 		= $_REQUEST['sb'];
		
		if(empty($sb_price))
			$sb_price = 0;
		
		$prod_id 	= GetProductID($prod_name);
		
		if($prod_name != '' && $price_id == ''){
			if(!CheckProductExist($prod_id)){
				AddProduct($user_id, $prod_id, $sp_price, $sb_price);
			}else{
				$error = $prod_name . ' უკვე არის სიაში!';
			}
		}else{
			SaveProduct($user_id, $price_id, $prod_id, $sp_price, $sb_price);
		}
		
        break;
    case 'disable':
		$prod_id = $_REQUEST['id'];
		DisableProduct($prod_id);
		
        break;
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Product Price List Functions
 * ******************************
 */

function AddProduct($user_id, $prod_id, $prod_price, $prod_sp_price)
{
	mysql_query("INSERT INTO `pricelist`
					(`user_id`, `production_id`, `price`, `price_wholesale`) 
				 VALUES
					($user_id, $prod_id, $prod_price, $prod_sp_price)");
}

function SaveProduct($user_id, $price_id, $prod_id, $prod_price, $prod_sp_price) 
{
	mysql_query("UPDATE
	    			`pricelist`
				 SET
				 	`user_id`			= $user_id,
				 	`production_id`		= $prod_id,
				    `price`				= $prod_price,
					`price_wholesale`	= $prod_sp_price
				 WHERE
					`id` = $price_id");
}

function GetSelfPrice($prod_id) 
{ 
    $res = mysql_fetch_assoc(mysql_query("
    										SELECT				ROUND(reserve.price , 2)  AS price		
											FROM  				reserve 
											LEFT JOIN      		production
											ON					reserve.production_id = production.id
											WHERE            	production.id = '$prod_id' 
											GROUP BY     		reserve.production_id
										 "));
	return round($res['price'], 2);
}

function GetLastPrice($prod_id)
{
	$res1 = mysql_fetch_assoc(mysql_query(" SELECT      `overhead_identity`.`identity_id` as dd
											FROM   		`overhead_identity`
											ORDER BY 	`overhead_identity`.`id` DESC
											LIMIT 		1
										"));
	if ($res1['dd'] == 0) {
		
	$res = mysql_fetch_assoc(mysql_query("
										SELECT 		 ROUND(`overhead_identity`.`price`, 2) as `price`
										FROM   		`overhead_identity`
										LEFT JOIN  `overhead_detail` ON overhead_identity.overhead_id = overhead_detail.overhead_id
										WHERE  		overhead_detail.goods_id =  '$prod_id'
										ORDER BY 	`overhead_identity`.`id` DESC
										LIMIT 		1
										"));
	}else {
	$res = mysql_fetch_assoc(mysql_query("
										SELECT 		ROUND(overhead_identity.price, 2) as price
										FROM   		overhead_identity
										LEFT JOIN 	production_identity
										ON     		overhead_identity.identity_id = production_identity.id
										WHERE  		production_identity.production_id = '$prod_id'
										ORDER BY 	overhead_identity.id DESC
										LIMIT 		1
										"));
	}
	return round($res['price'], 2);
	
}

function CheckProductExist($prod_id) 
{
    $res = mysql_fetch_assoc(mysql_query("SELECT `id`
										  FROM `pricelist`
										  WHERE `production_id` = $prod_id && `actived` = 1"));
	if($res['id'] != ''){
		return true;
	}
	return false;
}
	
function DisableProduct($prod_id)
{
    mysql_query("UPDATE `pricelist`
				 SET	`actived` = 0
				 WHERE	`id` = $prod_id ");
}

function GetProductID($prod_name) 
{
	$prod_name = htmlspecialchars($prod_name, ENT_QUOTES);
    $res = mysql_fetch_assoc(mysql_query("SELECT	`id`
										  FROM		`production`
										  WHERE		`name` = '$prod_name'"));
	return $res['id'];
}

function GetProduct($prod_id) 
{
    $res = mysql_fetch_assoc(mysql_query("SELECT	 				`pricelist`.`id` AS `id`, 
																	`production`.`name`,
																	`production`.`id` AS `prod_id`,
																	ROUND(reserve.price , 2) AS t_price,
																	`pricelist`.`price` AS `sp_price`, 
																	`pricelist`.`price_wholesale` AS `sb_price`
											FROM  					pricelist 
											LEFT JOIN      			production 
											ON                		pricelist.production_id = production.id
											LEFT JOIN          		reserve
											ON                     	pricelist.production_id = reserve.production_id
		    								WHERE                   pricelist.id = ' $prod_id '
											GROUP BY     			reserve.production_id
    		                                "));
	return $res;
}

function GetPage($res = '')
{
	$last_price = GetLastPrice($res['prod_id']);
	if($last_price == 0){
		$last_price = '';
	}
	$price		= $res['sp_price'];
	if (!empty($res)) {
		$percent	= round(((100*($price - $last_price))/$last_price), 2);
	}
	
	$data = '
	<div id="dialog-form">
	    <fieldset>
	    	<legend>ძირითადი ინფორმაცია</legend>
	    	
	    	<table cellpadding="0" cellspacing="0" border="0" class="dialog-form-table">
				<tr>
					<td style="width: 170px;"><label for="prod_name">დასახელება</label></td>
					<td>
						<div class="seoy-row" id="prod_name_seoy">
							<input type="text" id="prod_name" class="idle seoy-address" onblur="this.className=\'idle seoy-address\'" onfocus="this.className=\'activeField seoy-address\'" value="' . $res['name'] . '" />
							<button id="prod_name_btn" class="combobox">prod_name</button>
						</div>
					</td>
				</tr>
									
				<tr>
					<td><label for="t_price">თვით ღირებულება</label></td>
					<td><input type="text" id="t_price" disabled="disabled" class="idle price" value="' . $res['t_price'] . '" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" /></td>
				</tr>
				<tr>
					<td><label for="l_price">ბოლო შეძენის ფასი</label></td>
					<td><input type="text" id="l_price" disabled="disabled" class="idle price" value="' . $last_price . '" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" /></td>
				</tr>
				<tr>
					<td><label for="percent">ფასნამატი %</label></td>
					<td><input type="text" id="percent" class="idle price" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" value="' . $percent . '" /></td>
				</tr>
				<tr>
					<td><label for="sp_price">სარეალიოზაციო ფასი</label></td>
					<td><input type="text" id="sp_price" class="idle price" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" value="' . $price . '" /></td>
				</tr>
				<tr>
					<td><label for="sb_price">საბითუმო ფასი</label></td>
					<td><input type="text" id="sb_price" class="idle price" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" value="' . $res['sb_price'] . '" /></td>
				</tr>
			</table>
			<!-- ID -->
			<input type="hidden" id="prod_id" value="' . $res['id'] . '" />
        </fieldset>
    </div>
    ';
	return $data;
}
?>